package com.uroad.jilinpda.layer;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;

import com.uroad.jilinpda.activity.LoginActivity;
import com.uroad.jilinpda.common.CurrApplication;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.http.OkHttpNetWork;
import com.uroad.jilinpda.http.OkHttpNetWorkCallBack;
import com.uroad.jilinpda.modle.CheckVersionMDL;
import com.uroad.jilinpda.util.DownLoadUtils;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.widget.CustomScrollView;
import com.uroad.lib.data.Constant;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.sys.SystemUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import static com.uroad.jilinpda.webservice.BaseWS.getNewUrl;

public class MainLayer {

    private Activity context;
    private MainLayerCallBack callBack;
    private OkHttpNetWork netWork;//网络请求类
    private MainNetWorkCallBack netWorkCallBack;
    private String ticketid;
    private boolean isDownloading = false;
    private SingleDownloadTask downloadTask;


    public MainLayer(Activity context, MainLayerCallBack callBack){
        this.context = context;
        this.callBack = callBack;
        netWork = new OkHttpNetWork(context);
        netWorkCallBack = new MainNetWorkCallBack();
    }

    public boolean isOnLine(){
        ticketid = (String) SPUtils.get(context, GlobalData.sp_ticketid, "");
        if (TextUtils.isEmpty(ticketid)) {
            return true;
        } else {
//            loadData();
            return false;
        }
    }

    public void getVersionInfo() {
        String deviceuuid = CurrApplication.getInstance().getDeviceuuid();
        netWork.doAllUrlRequest(getNewUrl(ActivateWS.appVersion), ActivateWS.appVersionParams(deviceuuid, "HANDSET"), ActivateWS.appVersion, netWorkCallBack);
    }

    public void downLoad(String urlString){
        if (TextUtils.isEmpty(urlString)) {
            callBack.onFailure("更新链接错误");
        } else {
            if ("4G".equalsIgnoreCase(Constant.NET)) {
                callBack.onFailure("当前为4G网络，请连接WIFI并切换成外网后更新");
                return;
            }
            if (!isDownloading) {
                isDownloading = true;
                startDownload(urlString);
            }
        }
    }

    public void logout() {
        String deviceuuid = CurrApplication.getInstance().getDeviceuuid();
        DialogHelper.showLoading(context, "");
        netWork.doAllUrlRequest(getNewUrl(ActivateWS.logout),
                ActivateWS.logoutParams(ticketid, deviceuuid), ActivateWS.logout, netWorkCallBack);
    }

    private void startDownload(String urlString) {
        //方法二、使用http方式异步下载
        if (downloadTask != null && downloadTask.getStatus()== AsyncTask.Status.RUNNING) {
            return;
        }
        downloadTask = new SingleDownloadTask(urlString);
        downloadTask.execute();
    }

    public class SingleDownloadTask extends AsyncTask<String, Integer, String> {
        private File file;
        String urlString;

        public SingleDownloadTask(String urlString){
            this.urlString = urlString;
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                String fileName = urlString.substring(urlString.lastIndexOf("/")+1);
//                String fileName = "liaoningposcharge.apk";
                String filePath = Environment.getExternalStorageDirectory()+ File.separator + fileName;
                //新建要写入的文件
                file = new File(filePath);
                //如果文件不存在，则新建文件
                if (!file.exists()) {
                    file.createNewFile();
                }else{
                    file.delete();
                    file.createNewFile();
                }
                //获取url路径
                URL url = new URL(urlString);
                //获取url连接
                URLConnection connection = url.openConnection();
//                connection.setConnectTimeout(10 * 1000);
                //获取文件的总长度
                int length = connection.getContentLength();
                //				//显示文件大小
                //				Message msg = new Message();
                //				msg.what = length;
                //				handler.sendMessage(msg);
                //获取输入流
                InputStream is = connection.getInputStream();

                //获取输出流
                FileOutputStream os = new FileOutputStream(file);
                //通过字节读取，每次读取1024B
                byte[] array = new byte[1024];
                int sum = 0;
                int index = is.read(array);
                while (index != -1) {
                    //写出array，长度0-index
                    os.write(array, 0, index);
                    sum+=index;
                    //更新进度
                    publishProgress(sum, length);
                    index = is.read(array);
                }
                os.flush();
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
                file.delete();
                return "";
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //更新下载进度
            long progress = (long) values[0] * 100 / (long) values[1];
            callBack.downLoadCallBack(progress, 1);
            //            tv_content.setText(progress+"%");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            tripDialog.dismiss();
            callBack.downLoadCallBack(-1, 0);
            isDownloading = false;
            //下载完成 运行下载文件
            //            tv_ok.setText("下载完成");
            //            tv_ok.setEnabled(true);
            if (file != null && file.length() > 0) {
                String path = file.getAbsolutePath();
                if (!TextUtils.isEmpty(path)) { //文件不为空，且下载完成
                    Intent intent = DownLoadUtils.openFile(path);
                    context.startActivity(intent);

                    //                        int result = UpdateUtil.excuteSuCMD(path);
                    //                        if (result == 0) {
                    //                            LogUtil.d(TAG, "更新成功");
                    //                        } else {
                    //                            LogUtil.d(TAG, "更新失败");
                    //                        }
                }
            }else{
                LogUtil.d("posLoginActivity", "下载失败");
                callBack.onFailure("下载失败，请稍后重试");
            }
        }
    }

    /**
     * 接口回调
     */
    private class MainNetWorkCallBack implements OkHttpNetWorkCallBack {

        @Override
        public void OnHttpNetWork(String type) {
            if (callBack != null)
                callBack.onFailure(type+"NetWork");
        }

        @Override
        public void OnHttpFailure(String type, String msg) {
            if (callBack != null)
                callBack.onFailure(msg);
        }

        @Override
        public void OnHttpTaskComplete(String result, String type) {
            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            if (FastJsonUtils.GetJsonStatu1(jsonObject)) {
                if (ActivateWS.appVersion.equalsIgnoreCase(type)) {
                    //检查版本更新
                    String data = FastJsonUtils.getData(jsonObject);
                    final CheckVersionMDL mdl = FastJsonUtils.parseObjectJSON(data, CheckVersionMDL.class);
                    if (mdl != null) {
                        String version = CurrApplication.getInstance().appversion;
                        if (SystemUtil.isNeedUpdate(version, mdl.getMinversion())) {
                            callBack.appVersionCallBack(mdl);
                        }
                    }
                }
                if (type.equals(ActivateWS.logout)) {
                    DialogHelper.endLoading();
                    if (FastJsonUtils.GetJsonStatu1(jsonObject)) {
                        //退出登录

                        CurrApplication.getInstance().setUserLoginer(null);
                        SPUtils.remove(context, GlobalData.sp_ticketid);
                        SPUtils.remove(context, GlobalData.sp_useruuid);
                        SPUtils.remove(context, GlobalData.sp_username);
                        SPUtils.remove(context, GlobalData.sp_phone);
                        SPUtils.remove(context, GlobalData.sp_recocode);

                        callBack.loginOutCallBack();
                    }
                }
            }else{
                if (callBack != null)
                    callBack.onFailure(jsonObject.getString("msg"));
            }
        }

    }



    public interface MainLayerCallBack extends LayerCallBack{
        void appVersionCallBack(CheckVersionMDL mdl);//
        void loginOutCallBack();//
        void downLoadCallBack(long progress, int code);//coed 0下载完成  1更新下载%
    }
}
